package com.itheima.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.R;
import com.itheima.api.*;
import com.itheima.exception.ConsumerException;
import com.itheima.pojo.*;
import com.itheima.utils.AppJwtUtil;
import com.itheima.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class UmsAdminService {

    @DubboReference
    private UmsAdminServiceApi umsAdminServiceApi;

    @DubboReference
    private UmsAdminRoleRelationApi umsAdminRoleRelationApi;

    @DubboReference
    private UmsRoleMenuRelationApi umsRoleMenuRelationApi;

    @DubboReference
    private UmsMenuApi umsMenuApi;

    @DubboReference
    private UmsRoleApi umsRoleApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录返回token
     * @param param
     * @return
     */
    public R login(Map<String, String> param) {
        //获取用户名和密码
        String username = param.get("username");
        String password = param.get("password");

        //判断用户名密码是否存在
        if (StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            throw new ConsumerException("请输入用户名或密码!");
        }

        //判断用户名是否存在
        UmsAdmin umsAdmin=umsAdminServiceApi.findByName(username);
        if (ObjectUtil.isEmpty(umsAdmin)){
            throw new ConsumerException("该用户不存在!");
        }

        //如果存在,判断密码是否正确
        String truePassword=umsAdmin.getPassword();
        if (!StrUtil.equals(password,truePassword)){
            throw new ConsumerException("密码有误,请重试!");
        }

        //判断员工禁用还是启用
        if (umsAdmin.getStatus()!=1){
            throw new ConsumerException("该员工已被禁用,请联系管理员!");
        }

        //存入redis
        String redisKey="AUTH_USER_ID";
        stringRedisTemplate.opsForValue().set(redisKey, Convert.toStr(umsAdmin.getId()));

        //生成token
        String token = AppJwtUtil.getToken(umsAdmin.getId());
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", "Bearer ");
       /* Map<String, Object> result = new HashMap<>();
        result.put("data", map);
        result.put("code", 200);
        result.put("message", "操作成功");*/


        //密码正确,返回token
        return R.success(map);
    }

    /**
     * 获取用户信息
     * @param
     * @return
     */
    public R info() {
        //获取当前登录者的id
        Long userId = Convert.toLong(stringRedisTemplate.opsForValue().get("AUTH_USER_ID"));
        //1.根据用户名查找用户,获取用户头像
        //UmsAdmin umsAdmin = umsAdminServiceApi.findByName(name);
        //获取用户名
        UmsAdmin umsAdmin = umsAdminServiceApi.getAdminById(userId);
        String username = umsAdmin.getUsername();
        String icon = umsAdmin.getIcon();
        if (StrUtil.isEmpty(icon)){
            icon=new String("");
        }

        //2.根据用户id查找角色id
        //Long roleId=umsAdminRoleRelationApi.findByUmsId(umsAdmin.getId());
        List<UmsAdminRoleRelation> umsAdminRoleRelations = umsAdminRoleRelationApi.getByAdminId(userId);
        List<Long> roleIds = CollUtil.getFieldValues(umsAdminRoleRelations, "roleId", Long.class);
        //根据角色id查询角色信息
        List<UmsRole> umsRoles = umsRoleApi.getByIds(roleIds);
        List<String> roles = CollUtil.getFieldValues(umsRoles, "name", String.class);

        //3.根据角色id获取菜单id,返回菜单数据
        List<UmsRoleMenuRelation> umsRoleMenuRelationList=umsRoleMenuRelationApi.findMenuIdsByRoleIds(roleIds);
        List<Long> menuIds = CollUtil.getFieldValues(umsRoleMenuRelationList, "menuId",Long.class);

        //4.根据菜单id查询菜单信息
        List<UmsMenu> menuList=umsMenuApi.findMenus(menuIds);

        //5.封装数据
        Map<String,Object> result=new HashMap<>();
        result.put("icon",icon);
        result.put("menus",menuList);
        result.put("roles",roles);
        result.put("username",username);

        return R.success(result);
    }


    /**
     * 分页查询用户信息
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    public R findByPage(Integer pageNum, Integer pageSize, String keyword) {
       Page<UmsAdmin> pageInfo=umsAdminServiceApi.findByPage(pageNum,pageSize,keyword);
       PageResult pageResult=new PageResult();
       pageResult.setList(pageInfo.getRecords());
       pageResult.setPageNum(Convert.toInt(pageInfo.getCurrent()));
       pageResult.setPageSize(Convert.toInt(pageInfo.getSize()));
       pageResult.setTotal(Convert.toInt(pageInfo.getTotal()));
       pageResult.setTotalPage(Convert.toInt(pageInfo.getPages()));
       return R.success(pageResult);
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    public R deleteById(Integer id) {
        umsAdminServiceApi.deleteById(id);
        return R.success(null);
    }

    /**
     * 添加用户
     * @param umsAdmin
     * @return
     */
    public R saveUms(UmsAdmin umsAdmin) {
        //判断用户名是否为空
        if (StrUtil.isEmpty(umsAdmin.getUsername())){
            throw new ConsumerException("用户名不能为空");
        }
        //判断密码是否为空
        if (StrUtil.isEmpty(umsAdmin.getPassword())){
            throw new ConsumerException("密码不能为空");
        }

        //判断用户名是否存在
        UmsAdmin ums = umsAdminServiceApi.findByName(umsAdmin.getUsername());
        if (ObjectUtil.isNotEmpty(ums)){
            throw new ConsumerException("用户名已存在");
        }
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setLoginTime(new Date());
        umsAdminServiceApi.saveUms(umsAdmin);

        return R.success(null);
    }

    /**
     * 获取用户角色
     * @param id
     * @return
     */
    public R getRole(Integer id) {
        //根据用户id查询对应角色id
        List<UmsAdminRoleRelation> umsAdminRoleRelations = umsAdminRoleRelationApi.getByAdminId(Convert.toLong(id));
        List<Long> roleIds = CollUtil.getFieldValues(umsAdminRoleRelations, "roleId", Long.class);

        if (CollUtil.isEmpty(roleIds)){
            return R.success(new ArrayList<>());
        }
        //根据角色id查询对于角色信息
        List<UmsRole> umsRoles = umsRoleApi.getByIds(roleIds);

        return R.success(umsRoles);
    }


    /**
     * 修改用户信息
     * @param id
     * @param umsAdmin
     * @return
     */
    public R updateById(Integer id,UmsAdmin umsAdmin) {
        umsAdminServiceApi.updateById(id,umsAdmin);
        return R.success(null);
    }

    /**
     * 修改用户状态
     * @param id
     * @param status
     */
    public R updateStatus(Integer id, Integer status) {
        umsAdminServiceApi.updateStatus(id,status);
        return R.success(null);
    }

    /**
     * 根据用户id查找用户
     * @param id
     * @return
     */
    public R fingById(Integer id) {
        UmsAdmin umsAdmin=umsAdminServiceApi.findById(id);
        return R.success(umsAdmin);
    }

    /**
     * 修改指定用户密码
     * @param param
     * @return
     */
    public R updatePassword(Map<String, String> param) {
        //获取前端数据
        String newPassword = param.get("newPassword");
        String oldPassword = param.get("oldPassword");
        String username = param.get("username");

        //根据用户名查找用户和密码
        UmsAdmin umsAdmin = umsAdminServiceApi.findByName(username);
        String password = umsAdmin.getPassword();

        //比较密码是否一致
        if (!StrUtil.equals(password,oldPassword)){
            throw new ConsumerException("密码不一致,修改失败");
        }

        //如果一致修改密码
        umsAdmin.setPassword(newPassword);
        umsAdminServiceApi.updateById(Convert.toInt(umsAdmin.getId()),umsAdmin);

        return R.success(null);
    }

    /**
     * 刷新token
     * @return
     */
    public R refreshToken() {
        String userId = stringRedisTemplate.opsForValue().get("AUTH_USER_ID");
        String token = AppJwtUtil.getToken(Convert.toLong(userId));
        return R.success(token);
    }
}
